<template>
  <!-- 搜索栏 start -->
  <el-row>
    <el-col :span="5">
      <div class="grid-content ep-bg-purple-dark">
        <el-input v-model.trim="kw" placeholder="请输入姓名或身份证号" class="w-100 m-2" />
      </div>
    </el-col>
    <el-col :span="1">
    </el-col>
    <el-col :span="4" class="m-2">
      <el-button type="primary" @click="loadData(1)">查询</el-button>
    </el-col>
    <el-col :span="10">
    </el-col>
    <el-col :span="4" class="m-2">
      <el-button type="danger" @click="addDialogVisible = true">新增电子就诊卡</el-button>
    </el-col>
  </el-row>
  <div style="margin-top: 40px;"></div>
  <!-- 搜索栏 end -->
  <!-- 表格栏 start -->
  <el-row class="m-2">
    <el-col :span="24">
      <el-table :data="data.records" style="width:100%;" v-loading="loading">
        <el-table-column type="expand">
          <template #default="props">
            <div>
              <p class="indent">关联用户: {{ props.row.customerName }}</p>
              <p class="indent">关系: {{ props.row.relationship }}</p>
              <p class="indent">家庭住址: {{ props.row.addr }}</p>
              <p class="indent">注册时间: {{ props.row.createdate }}</p>
              <p class="indent">注册渠道: {{ props.row.channelName }}</p>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="id" label="序号" align="center" width="80" />
        <el-table-column prop="realname" label="姓名" align="center" />
        <el-table-column prop="gender" label="性别" align="center" :formatter="formatGender"/>
        <el-table-column prop="idnumber" label="身份证" align="center" />
        <el-table-column prop="birthdate" label="出生日期" align="center" />
        <el-table-column prop="phone" label="手机号" align="center" />
        <el-table-column prop="cardtypeName" label="卡类型" align="center" />
        <el-table-column fixed="right" label="Operations" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="showEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!-- 表格栏 end -->
  <div style="margin-top: 20px;"></div>

  <el-row>
    <el-col :span="20">
      <el-pagination background layout="prev, pager, next" :total="1" :page-count="data.pages"
        @current-change="handleCurrentChange" />
    </el-col>
    <el-col :span="4">
      <el-select v-model="ps" class="w-20 m-2" placeholder="每页行数" @change="loadData(1)">
        <el-option v-for="item in pageSizes" :key="item" :label="item" :value="item" />
      </el-select>
    </el-col>
  </el-row>

  <!-- 新增常数据项对话框 start -->
  <el-dialog v-model="addDialogVisible" title="新增" @close="closeDialog">
    <el-form :model="editform" :rules="rules" label-width="100px">
      <el-form-item label="编号" prop="id">
        <el-input v-model="editform.id" autocomplete="off" />
      </el-form-item>

      <el-form-item label="姓名" prop="realname">
        <el-input v-model="editform.realname" autocomplete="off" />
      </el-form-item>

      <el-form-item label="身份证号" prop="idnumber">
        <el-input v-model="editform.idnumber" autocomplete="off" />
      </el-form-item>

      <el-form-item label="出生日期" prop="birthdate">
        <el-input v-model="editform.birthdate" autocomplete="off" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="editform.gender" class="m-2" placeholder="请选择性别">
          <el-option label="男" value="71" />
          <el-option label="女" value="72" />
        </el-select>
      </el-form-item>

      <el-form-item label="就诊卡类型" prop="cardtype">
        <el-select v-model="editform.cardtype" filterable class="m-2" placeholder="请选择卡类型">
          <el-option label="普通卡" value="185" />
          <el-option label="医保卡" value="186" />
        </el-select>
      </el-form-item>

      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="editform.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="家庭住址" prop="addr">
        <el-input v-model="editform.addr" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="add">
          新增
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 新增常数据类别对话框  end-->

    <!-- 编辑常数据项对话框 start -->
    <el-dialog v-model="editDialogVisible" title="新增" @close="closeDialog">
    <el-form :model="editform" :rules="rules" label-width="100px">
      <el-form-item label="编号" prop="id">
        <el-input v-model="editform.id" autocomplete="off" />
      </el-form-item>

      <el-form-item label="姓名" prop="realname">
        <el-input v-model="editform.realname" autocomplete="off" />
      </el-form-item>

      <el-form-item label="身份证号" prop="idnumber">
        <el-input v-model="editform.idnumber" autocomplete="off" />
      </el-form-item>

      <el-form-item label="出生日期" prop="birthdate">
        <el-input v-model="editform.birthdate" autocomplete="off" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="editform.gender" class="m-2" placeholder="请选择性别">
          <el-option label="男" value="71" />
          <el-option label="女" value="72" />
        </el-select>
      </el-form-item>

      <el-form-item label="就诊卡类型" prop="cardtype">
        <el-select v-model="editform.cardtype" filterable class="m-2" placeholder="请选择卡类型">
          <el-option label="普通卡" value="185" />
          <el-option label="医保卡" value="186" />
        </el-select>
      </el-form-item>

      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="editform.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="家庭住址" prop="addr">
        <el-input v-model="editform.addr" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="editSave">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 编辑常数据类别对话框  end-->



</template>

<script setup>
import { ref, onMounted } from 'vue'
import { fetchData, postReq } from '../../utils/api'
import router from '../../router';
import { ElMessageBox } from 'element-plus'
import { formatGender } from '../../utils/utils'

//data start
const loading = ref(false)
const data = ref({
  records: []
})
//搜索框
const kw = ref('')
//每页行数
const ps = ref(10)
const pageSizes = [10, 20, 30, 50]
//新增对话框是否显示
const addDialogVisible = ref(false)
//编辑对话框是否显示
const editDialogVisible = ref(false)


//表单对象
const editform = ref({
  "id": null,
  "realname": "",
  "gender": "",
  "idnumber": "",
  "birthdate": "",
  "phone": "",
  "addr": "",
  "cardtype": null,
  "cardNo": "",
  "customerId": null,
  "Relationship": null,
  "createDate": null,
  "channel": null,
  "delMark": 1
});

onMounted(async () => {
  loadData(1)
});

//加载数据
async function loadData(pn) {
  loading.value = true;
  let url = `/medicalCard/page?count=${ps.value}&pn=${pn}`;

  if (kw !== '') {
    url += `&keyword=${kw.value}`;
  }
  try {
    const result = await fetchData(url, null);
    if (result.result) {
      data.value = result.data
      loading.value = false
    } else {
      if (result.errMsg == '未登录')
        router.push('/login')
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

//新增内容
function add(){
  editform.value.channel = 182
  editform.value.delMark = 1
  console.log(editform.value)
	postReq("/medicalCard/add",editform.value).then(resp=>{
		if(resp.data.result){
			addDialogVisible.value=false
			ElMessageBox.alert('新增成功', '提示',{})
      loadData(1)
		}else{
			if(result.errMsg=='未登录')
				router.push('/login')
				
			ElMessageBox.alert(resp.data.errMsg, '提示',{})
		}	
	})
}

//保存编辑内容
function editSave(){
  console.log(editform.value)

  let currentGender = editform.value.gender
  if (currentGender === "男"){
    editform.value.gender =71 
  }else if (currentGender ==="女"){
    editform.value.gender=72
  }
	postReq("/medicalCard/update",editform.value).then(resp=>{
		if(resp.data.result){
			editDialogVisible.value=false
			loadData(data.value.current)
			ElMessageBox.alert('修改成功', '提示',{})
			
		}else{
			if(result.errMsg=='未登录')
				router.push('/login')
			ElMessageBox.alert(resp.data.errMsg, '提示',{})
		}
		
	})
}


//分页
function handleCurrentChange(number) {
  loadData(number)
}

//显示编辑框
function showEdit(item){
  console.log(item)
  editform.value=item

  //处理展示这块的逻辑
  let currentGender = editform.value.gender
  if (currentGender ===71){
    editform.value.gender ="男"
  }else if(currentGender ===72){
    editform.value.gender="女"
  }

  let currentCardType = editform.value.cardtype
  if(currentCardType ==="185"){
    editform.value.cardtype="普通卡"
  }else if(currentCardType ==="186"){
    editform.value.cardtype="医保卡"
  }

	editDialogVisible.value=true
}

//取消
function cancelEdit(){
  console.log("取消操作");
  editDialogVisible.value=false
    loadData(1);



}

//删除
function del(id) {
  ElMessageBox.confirm(
    '确认是否删除?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
  .then(() => {
    // 用户点击了确认按钮
    var formData = new FormData();
    formData.append("id", id);
    postReq("/medicalCard/del", formData).then(resp => {
      if (resp.data.result) {
        loadData(data.value.current);
        ElMessageBox.alert('删除成功', '提示', {});
      } else {
        if (result.errMsg == '未登录') {
          router.push('/login');
        }
        ElMessageBox.alert(resp.data.errMsg, '提示', {});
      }
    });
  })
  .catch((err) => {
    // 用户点击了取消按钮或关闭了对话框
    if (err && err.message === "cancel") {
      console.log("用户取消了操作");
    } else {
      console.error('意外错误:', err);
    }
  });
}


</script>

<style>
.indent {
  text-indent: 60px; /* 调整此值以控制缩进距离 */
}
</style>